package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PutMapping;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public List<BrandDTO> queryBrandByCid(Long id) {
        //先查询中间表，在查找数据
        // SELECT b.id,b.name,b.image,b.letter
        //FROM tb_category_brand cb
        //INNER JOIN tb_brand b ON cb.brand_id = b.id
        //WHERE cb.category_id = #{cid}
        List<Brand> list = getBaseMapper().queryById(id);
        //转换
        return BrandDTO.convertEntityList(list);
    }

    @Override
    public PageDTO<BrandDTO> queryByPage(String key, Integer page, Integer rows) {
        //需要先判断分页是正常分页码数，不能是负数
        if (page <= 0 || rows <=0 ){
            throw new LyException(400 , "当前页码范围有问题");
        }
        //条件查询
        //模糊查询需要看数据是否有，需先判断是否有key值存在 true有数据，false无数据
        boolean isNotBlank = StringUtils.isNotBlank(key);
        //先模糊查询，再做分页查询（模糊查询需要看key是否有数据，有就条件查询没有直接跳过进行分页查询）
        //                          判断是否有key值，有就查询
        Page<Brand> pages = query().like(isNotBlank,"name" ,key).or().eq(isNotBlank,"letter",key)
                .page(new Page<>(page ,rows));
                //分页查询
        //查询到的数据封装
        List<BrandDTO> brandDTOS = BrandDTO.convertEntityList(pages.getRecords());

        return new PageDTO<>(pages.getTotal(),pages.getPages(),brandDTOS);
    }

    /**
     * 新增品牌
     * @param brandDTO  新增品牌信息
     *                  无
     */
    @Transactional//开启事务
    @Override
    public void saveByBrand(BrandDTO brandDTO) {
        //需要先增加品牌
        Brand brand = brandDTO.toEntity(Brand.class);
        boolean isBrand = save(brand);
        //判断是否成功，如果添加品牌成功向下走，没有报错
        if (!isBrand){
            throw new LyException( 500 , "新增品牌失败");
        }
        Long brandId = brand.getId();
        //添加中间表数据
        //获取分类id
        List<Long> categoryIds = brandDTO.getCategoryIds();
        //获取新增数据,使用stream流
        List<CategoryBrand> list = categoryIds.stream()
                .map(categoryId -> CategoryBrand.of(categoryId, brandId))
                .collect(Collectors.toList());
        //新增中间表
        categoryBrandService.saveBatch(list);

    }

    /**
     * 更新品牌
     * @param brandDTO 修改的数据
     *     无
     */
    @Transactional
    @Override
    public void updateBrand(BrandDTO brandDTO) {
        //修改品牌
        boolean isbrand = updateById(brandDTO.toEntity(Brand.class));
        if (!isbrand){
            throw new LyException(500 , "更新品牌失败！");
        }
        //先删除中间表
        //根据品牌id删除中间表数据
        QueryWrapper<CategoryBrand> brindList = new QueryWrapper<CategoryBrand>().eq("brand_id", brandDTO.getId());
        isbrand = categoryBrandService.remove(brindList);
        if (!isbrand){
            throw new LyException(500 ,"更新品牌失败，删除中间表数据出错！");
        }
        //再添加中间表
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream()
                .map(brandId -> CategoryBrand.of(brandId,brandDTO.getId())).collect(Collectors.toList());
        categoryBrandService.saveBatch(list);
    }

    @Transactional
    @Override
    public void deleteBrandById(Long id) {
        //删除品牌
        removeById(id);
        //删除中间表
        categoryBrandService.remove(new QueryWrapper<CategoryBrand>()
                .eq("brand_id" ,id));
    }


}
